import {
	getss
} from './md5.js';
import {
	CustomError
} from './utils.js';
let baseURL = 'https://sm.2sxzw.com/api';
// let baseURL = 'https://mh.hqxwl.cn/api';
export const version = '1.0.4'
// #ifdef H5
// baseURL = '/api';
if (process.env.NODE_ENV === 'production') {
	baseURL = '/api';
}
// #endif
function handResult(res, resolve, rejected) {
	if (res.err_no == 0) {
		resolve(res);
	} else if (res.err_no == 4000) {
		uni.reLaunch({
			url: `/src/pages/My/AccountError/AccountError?err_msg=${res.err_msg}&uid=${res.data.uid}&kefu_url=${encodeURIComponent(res.data.kefu_url)}`
		})
	} else if (res.err_no == 1002) { // 需要重新登陆的
		if (getApp) {
			getApp.globalData = null
		}
		uni.removeStorageSync('jwt_token');
		uni.$emit('userUpdate', {
			userData: null
		})
		uni.showToast({
			icon: 'none',
			title: res.err_msg,
			duration: 3500
		});
		rejected(null);
	} else if (res.err_no == 1003) { // 显示toase
		if (res.err_msg) {
			uni.showToast({
				icon: 'none',
				title: res.err_msg,
				duration: 3500
			});
		}
		rejected(null);
	} else if (res.err_no == 1004) { // 显示modal
		uni.showModal({
			content: res.err_msg,
			showCancel: false
		})
		rejected(null);
	} else if (res.err_no == 2001) { // 跳到积分页
		uni.showModal({
			title: '积分不足',
			content: res.err_msg,
			confirmText: '充值',
			success: function(res) {
				if (res.confirm) {
					uni.navigateTo({
						url: '/src/pages/My/Pay/pay?currentIndex=0'
					});
				}
			}
		});
		rejected(null);
	} else if (res.err_no == 2002) { // 跳到会员页面
		uni.showModal({
			title: '开通会员',
			content: res.err_msg,
			confirmText: '开通',
			success: function(res) {
				if (res.confirm) {
					uni.navigateTo({
						url: '/src/pages/My/Pay/pay?currentIndex=1'
					});
				}
			}
		});
		rejected(null);
	} else {
		rejected(CustomError(res.err_no, res.err_msg));
	}
}

function myRequest(options, showLoding = true, parentHandErr = true) {
	let ss = getss();
	const header = options.header || {};
	const initData = options.data || {};
	let globalData = null
	if (getApp()) {
		globalData = getApp().globalData
	} else {
		globalData = options.data.globalData
	}
	if (!globalData) {
		console.log('globalData不存在，请求终止了')
	}
	options.header = {
		appid: globalData.appid,
		'jwt-token': (globalData.userData && globalData.userData.jwt_token) || uni.getStorageSync(
			'jwt_token'),
		'content-type': 'application/x-www-form-urlencoded; charset=utf-8',
		S: ss[0],
		Ss: ss[1],
		version: version,
		platform: globalData.platform,
		...header
	};
	if (initData.hasOwnProperty("globalData")) {
		delete initData["globalData"]
	}

	options.data = {
		// unionid: options.data.unionid || uni.getStorageSync('unionid'),
		version: version,
		platform: globalData.platform,
		...initData
	};
	return new Promise((resolve, rejected) => {
		if (showLoding) {
			uni.showLoading({
				title: '加载中'
			});
		}
		// console.log('===',options.url)
		uni.request({
			header: options.header,
			url: baseURL + options.url,
			data: options.data,
			method: options.method || 'GET',
			// timeout: 60000,
			success(res) {
				// console.log(options.url,res)
				if (showLoding) {
					uni.hideLoading();
				}
				if (res.statusCode === 200) {
					res = res.data;
					handResult(res, resolve, rejected)
				} else if (res.statusCode >= 400 && res.statusCode < 600) {
					uni.showToast({
						icon: 'none',
						title: '服务器内部错误',
						duration: 3500
					});
					rejected(null);
				} else {
					//请求状态码不对，一般是服务器挂了
					if (parentHandErr) {
						uni.showToast({
							icon: 'none',
							title: '服务器异常',
							duration: 3500
						});
						console.log(res.data);
					}
					rejected(res);
				}
			},
			fail(err) {
				// console.error(err)
				if (showLoding) {
					uni.hideLoading();
				}
				if (parentHandErr) {
					if (err.errMsg.includes('-1009')) {
						uni.showToast({
							icon: 'none',
							title: '似乎已断开与互联网的连接',
							duration: 3500
						});
					} else {
						uni.showToast({
							icon: 'none',
							title: '网络异常，请检查网络',
							duration: 3500
						});
					}
				}
				rejected(err);
			}
		});
	});
}
myRequest.get = function(url, data, showLoding = true, parentHandErr = true) {
	return myRequest({
			url: url,
			data: data,
			method: 'GET'
		},
		showLoding,
		parentHandErr
	);
};
myRequest.post = function(url, data, showLoding = true, parentHandErr = true) {
	return myRequest({
			url: url,
			data: data,
			method: 'POST'
		},
		showLoding,
		parentHandErr
	);
};

export function upload_file(options, showLoding = true, parentHandErr = true, upload_callback = null) {
	let ss = getss();
	const header = options.header || {};
	const initData = options.formData || {};
	options.header = {
		appid: getApp().globalData.appid,
		'jwt-token': (getApp().globalData.userData && getApp().globalData.userData.jwt_token) || uni.getStorageSync(
			'jwt_token'),
		S: ss[0],
		Ss: ss[1],
		version: version,
		platform: getApp().globalData.platform,
		...header
	};
	options.formData = {
		version: version,
		platform: getApp().globalData.platform,
		...initData
	};
	return new Promise((resolve, rejected) => {
		if (showLoding) {
			uni.showLoading({
				title: '加载中'
			});
		}
		let uploadTask = uni.uploadFile({
			header: options.header,
			url: baseURL + options.url,
			files: [options.file],
			name: options.file.name,
			timeout: 600000,
			filePath: options.file.uri,
			formData: options.formData,
			success: (res) => {
				// console.log(res)
				uni.hideLoading();
				if (res.statusCode === 200) {
					res = res.data;
					if (typeof res === 'string') {
						res = JSON.parse(res);
					}
					handResult(res, resolve, rejected)
				} else if (res.statusCode >= 400 && res.statusCode < 600) {
					uni.showToast({
						icon: 'none',
						title: '服务器内部错误',
						duration: 3500
					});
					rejected(null);
				} else {
					//请求状态码不对，一般是服务器挂了
					if (parentHandErr) {
						uni.showToast({
							icon: 'none',
							title: '服务器异常',
							duration: 3500
						});
						console.log(res.data);
					}
					rejected(res);
				}
			},
			fail: (e) => {
				if (parentHandErr) {
					uni.showToast({
						icon: 'error',
						title: '网络请求失败',
						duration: 3000
					});
				}
				rejected(e);
				console.log(e);
			}
		});
		if (upload_callback) {
			upload_callback(uploadTask)
		}
	});
}

// 模块导出
export default myRequest;